package org.wbd.pklib.db;

import javax.persistence.*;

import org.wbd.pklib.db.logic.LoanLogic;

import static javax.persistence.GenerationType.IDENTITY;
import java.util.HashSet;
import java.util.Set;

/**
 * Klasa reprezentująca obiekt egzemplarza danej ksiazki 
 * ,obiekt tej klasy jest obiektowym odzwierciedleniem
 * rekord w tabeli "item"
 */
@Entity
@Table(name = "item")
@AssociationOverrides({
		@AssociationOverride(name = "itemJoin.book", joinColumns = @JoinColumn(name = "isbn")),
		@AssociationOverride(name = "itemJoin.user", joinColumns = @JoinColumn(name = "userId")),
		@AssociationOverride(name = "itemJoin.repo", joinColumns = @JoinColumn(name = "repoId")) })
public class Item implements java.io.Serializable {

	private ItemJoin itemJoin = new ItemJoin();
	private Integer itemId;

	public Item() {

	}

	public Item(ItemJoin itemJoin, Integer itemId) {
		this.itemJoin = itemJoin;
		this.itemId = itemId;

	}

	@EmbeddedId
	public ItemJoin getItemJoin() {
		return itemJoin;
	}

	public void setItemJoin(ItemJoin itemJoin) {
		this.itemJoin = itemJoin;
	}

	@Transient
	public User getUser() {
		return getItemJoin().getUser();
	}

	public void setUser(User user) {
		getItemJoin().setUser(user);
	}

	@Transient
	public Repo getRepo() {
		return getItemJoin().getRepo();
	}

	public void setRepo(Repo repo) {
		getItemJoin().setRepo(repo);
	}

	@Transient
	public Book getBook() {
		return getItemJoin().getBook();
	}

	public void setBook(Book book) {
		getItemJoin().setBook(book);
	}


	@Column(name = "itemId", nullable = true, unique = true)
	public Integer getItemId() {
		return itemId;
	}

	public void setItemId(Integer itemId) {
		this.itemId = itemId;
	}
	@Transient
	public boolean isLent() {
		LoanLogic loanLogic = LoanLogic.getInstance();
		Loan loan = (Loan) (loanLogic.getLoanByItem(this).getResultObject());
		if (loan != null)
			return true;
		return false;
	}


	public boolean equals(Object o) {
		if (this.itemId == ((Item) o).getItemId()) {
			return true;
		}
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		Item that = (Item) o;

		if (getItemJoin() != null ? !getItemJoin().equals(that.getItemJoin())
				: that.getItemJoin() != null)
			return false;

		return true;
	}

	public int hashCode() {
		return (getItemJoin() != null ? getItemJoin().hashCode() : 0);
	}

	@Override
	public String toString() {
		return "Item [itemId=" + itemId + ", getUser()="
				+ getUser().getUserId() + ", getRepo()="
				+ getRepo().getRepoId() + "]";
	}

}
